package cc.rengu.igas.mcps.core.service.trans.common;

import cc.rengu.igas.mcps.common.enums.RespCodeEnum;
import cc.rengu.igas.mcps.core.service.base.ManageService;
import cc.rengu.igas.mcps.facade.request.PosParamListQueryRequest;
import cc.rengu.igas.mcps.facade.response.PosParamListQueryResponse;
import cc.rengu.igas.share.core.model.EmvParamInfo;
import cc.rengu.igas.share.core.realize.BompService;
import cc.rengu.igas.share.core.realize.impl.BompServiceImpl;
import cc.rengu.oltp.service.common.constant.AppParamConstant;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.DateUtil;
import cc.rengu.oltp.utility.util.HexUtil;
import cc.rengu.oltp.utility.util.TLVDataUtil;
import com.alibaba.fastjson.JSON;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TermParamListQueryService extends ManageService {
    @Override
    protected Object bizBeforeCust() throws Exception {
        PosParamListQueryRequest posParamListQueryRequest = new PosParamListQueryRequest();
        ConvertUtil.convertOutput(posParamListQueryRequest);
        return posParamListQueryRequest;
    }

    @Override
    protected BizResponse bizProcessCust(Object request) throws Exception {
        /*初始化request*/
        PosParamListQueryRequest posParamListQueryRequest = (PosParamListQueryRequest) request;
        /*初始化返回报文response*/
        PosParamListQueryResponse posParamListQueryResponse = new PosParamListQueryResponse();
        BizResponse bizResponse = new BizResponse();
        /*获取上传参数类型*/
        String paramType = posParamListQueryRequest.getParamType();
        /*获取已收参数列表条数*/
        String loadedCnt = posParamListQueryRequest.getLoadedCnt();
        /*初始化返回列表内容*/
        String msg = "0";
        /*初始化参数信息List*/
        BompService bompService = new BompServiceImpl();
        List<EmvParamInfo> emvParamInfoList = bompService.getEmvParamInfo(posParamListQueryRequest.getHeader().getInstId());
        if (null == emvParamInfoList || emvParamInfoList.isEmpty()) {
            rglog.error("EMV配置参数为空!");
            throw new BizException(RespCodeEnum.QUERY_DATA_IS_NULL.getRespCode(), RespCodeEnum.QUERY_DATA_IS_NULL.getRespDesc());
        }
        /* Step 1 ：获取参数列表*/
        /*判断参数类型*/
        /*pos基本参数*/
        if ("372".equals(paramType)) {
            /*ic卡公钥参数列表获取*/
            emvParamInfoList = emvParamInfoList.stream().filter(item -> item.getUsageKey().equals("1")).collect(Collectors.toList());
            /*判断返回值是否为空*/
            if (!emvParamInfoList.isEmpty()) {
                /*调用方法拼接返回值*/
                msg = assemblyMsgWithIcKey(emvParamInfoList, loadedCnt);
            }
        } else {
            /*ic卡参数列表获取*/
            emvParamInfoList = emvParamInfoList.stream().filter(item -> item.getUsageKey().equals("0")).collect(Collectors.toList());
            /*判断返回值是否为空*/
            if (!emvParamInfoList.isEmpty()) {
                msg = assemblyMsgWithIcParam(emvParamInfoList, loadedCnt);
            }
        }
        /* Step 2 ：重组响应结果 */
        /*设置response 属性值*/
        posParamListQueryResponse.setParaList(msg);
        posParamListQueryResponse.setSysDate(DateUtil.getCurrentDate());
        posParamListQueryResponse.setSysTime(DateUtil.getCurrentTime());
        /*初始化*/
        bizResponse.setRspSysId(AppParamConstant.IGAS);
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(posParamListQueryResponse);
        return bizResponse;
    }

    @Override
    protected void bizAfterCust(Object response) throws Exception {
        BizResponse bizResponse = (BizResponse) response;
        PosParamListQueryResponse posParamListQueryResponse = (PosParamListQueryResponse) bizResponse.getResult();
        ConvertUtil.convertInput(posParamListQueryResponse);
    }

    /*
     * 拼接返回ic卡公钥列表内容
     * @param list
     * @param loadedCnt
     * */
    protected String assemblyMsgWithIcKey(List<EmvParamInfo> list, String loadedCnt) throws Exception {
        /*初始化要拼装的值*/
        StringBuilder msg;
        /*获取list的size*/
        int keyCount = list.size();
        /*转换上传已收参数列表条数*/
        int loadCount = (Integer.parseInt(loadedCnt));
        /*初始化RID tag*/
        String tagOfRID = "9F06";
        String tlvOfRID;
        /*初始化索引 tag*/
        String tagOfIndex = "9F22";
        String tlvOfIndex;
        /*初始化有效期 tag*/
        String tagOfEFFC_DATE = "DF05";
        String tlvOfEFFC_DATE;
        /*size小于等于8 一个报文可以放下所有信息的情况*/
        int countNum;
        if (keyCount <= 8) {
            /*字符1的16进制显示*/
            msg = new StringBuilder("31");
            countNum = keyCount;
        } else if (loadCount + 8 < keyCount) {
            /*数据长度大于8*/
            msg = new StringBuilder("32");
            countNum = loadCount + 8;
        } else {
            /*数据长度大于8*/
            msg = new StringBuilder("33");
            countNum = keyCount;
        }
        for (int i = loadCount; i < countNum; i++) {
            /*AID,索引,有效期;*/
            /*组装RID*/
            tlvOfRID = TLVDataUtil.packageTLVData(tagOfRID, list.get(i).getParamId().trim());
            /*组装索引*/
            tlvOfIndex = TLVDataUtil.packageTLVData(tagOfIndex, list.get(i).getParamIndex().trim());
            /*组装有效期*/
            Map map = JSON.parseObject(list.get(i).getParamValue(), Map.class);
            /*有效日期特殊处理*/
            String effectDate = HexUtil.StringtoHex(((String) map.get("EFFC_DATE")).trim());
            tlvOfEFFC_DATE = TLVDataUtil.packageTLVData(tagOfEFFC_DATE, effectDate);
            /*拼装*/
            rglog.debug("tlvofRID:<{}>,tlvOfIndex<{}>,tlvOfEFFC_DATE<{}>", tlvOfRID, tlvOfIndex, tlvOfEFFC_DATE);
            msg.append(tlvOfRID).append(tlvOfIndex).append(tlvOfEFFC_DATE);
        }
        return msg.toString();
    }

    /*
     * 拼接返回ic卡参数列表内容
     * @param list
     * @param loadedCnt
     * */
    protected String assemblyMsgWithIcParam(List<EmvParamInfo> list, String loadedCnt) {
        /*初始化要拼装的值*/
        StringBuilder msg;
        /*获取list的size*/
        int keyCount = list.size();
        /*转换上传已收参数列表条数*/
        int loadCount = (Integer.parseInt(loadedCnt));
        /*初始化AID tag*/
        String tagOfAID = "9F06";
        /*初始化tlv AID值*/
        String tlvOfAID;
        /*判断size大小*/
        /*size小于等于13 一个报文可以放下所有信息的情况*/
        int countNum;
        if (keyCount <= 8) {
            /*字符1的16进制显示*/
            msg = new StringBuilder("31");
            countNum = keyCount;
        } else if (loadCount + 8 < keyCount) {
            /*数据长度大于8*/
            msg = new StringBuilder("32");
            countNum = loadCount + 8;
        } else {
            /*数据长度大于8*/
            msg = new StringBuilder("33");
            countNum = keyCount;
        }
        for (int i = loadCount; i < countNum; i++) {
            /*AID组装AID*/
            tlvOfAID = TLVDataUtil.packageTLVData(tagOfAID, list.get(i).getParamId().trim());
            rglog.debug("tagOfAID:<{}>", tagOfAID);
            msg.append(tlvOfAID);
        }
        return msg.toString();
    }
}








